﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.IO;

namespace RJ.Objects.Workers
{
    public class JsonFileReaderWriter<TType>
    {
        private string path;
        private TType loadedObject;

        public JsonFileReaderWriter(string filePath)
        {
            path = filePath;
        }

        public TType Read()
        {
            JsonSerializer serializer = JsonSerializer.Create();
            TType readObject = default(TType);

            using (FileStream file = File.OpenRead(path))
            {
                using (JsonReader reader = new JsonTextReader(new StreamReader(file)))
                {
                    readObject = serializer.Deserialize<TType>(reader);
                }
            }

            return readObject;
        }

        public void Write(TType value)
        {
            JsonSerializer serializer = JsonSerializer.Create();

            using (FileStream file = File.Create(path))
            {
                using (StreamWriter stream = new StreamWriter(file))
                {
                    serializer.Serialize(stream, value);
                }
            }
        }
    }
}
